<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="item_id" label="收藏项目ID" required>
        <uni-easyinput placeholder="收藏项目的ID，根据item_type不同对应不同表的_id" v-model="formData.item_id" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="item_type" label="收藏类型" required>
        <uni-data-checkbox v-model="formData.item_type" :localdata="formOptions.item_type_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="item_title" label="收藏项目标题">
        <uni-easyinput placeholder="收藏项目的标题/名称" v-model="formData.item_title" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="item_image" label="收藏项目图片">
        <uni-easyinput placeholder="收藏项目的缩略图/头像" v-model="formData.item_image" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="item_description" label="收藏项目描述">
        <uni-easyinput placeholder="收藏项目的描述/摘要" v-model="formData.item_description" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="item_selltype" label="商品售卖类型">
        <uni-easyinput placeholder="商品售卖类型（仅当item_type为1时有值） 0新售,1转售" type="number" v-model="formData.item_selltype"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="item_price" label="商品价格">
        <uni-easyinput placeholder="商品价格（仅当item_type为1时有值）" v-model="formData.item_price" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="item_author" label="作者/商户">
        <uni-easyinput placeholder="文章作者或商品商户（仅当item_type为1或2时有值）" v-model="formData.item_author" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="item_rating" label="评分">
        <undefined v-model="formData.item_rating"></undefined>
      </uni-forms-item>
      <uni-forms-item name="create_date" label="收藏时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.create_date"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="user_id" label="收藏者ID" required>
        <uni-easyinput placeholder="收藏者ID，参考uni-id-users表" v-model="formData.user_id"></uni-easyinput>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/intangible_usercollection.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'intangible_usercollection';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "item_id": "",
        "item_type": null,
        "item_title": "",
        "item_image": "",
        "item_description": "",
        "item_selltype": 0,
        "item_price": "",
        "item_author": "",
        "item_rating": null,
        "create_date": null,
        "user_id": ""
      }
      return {
        formData,
        formOptions: {
          "item_type_localdata": [
            {
              "value": 1,
              "text": "商品"
            },
            {
              "value": 2,
              "text": "文章"
            },
            {
              "value": 3,
              "text": "商户"
            },
            {
              "value": 4,
              "text": "非遗传人"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("item_id,item_type,item_title,item_image,item_description,item_selltype,item_price,item_author,item_rating,create_date,user_id").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
